package com.zidian.teacher.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.teacher.R;
import com.zidian.teacher.activity.AboutActivity;
import com.zidian.teacher.activity.LoginActivity;
import com.zidian.teacher.activity.PersonOptionActivity;
import com.zidian.teacher.activity.TeacherChangeActivity;
import com.zidian.teacher.activity.TeacherSetPasswordActivity;
import com.zidian.teacher.application.MyApplication;
import com.zidian.teacher.bean.TeacherMessage;
import com.zidian.teacher.common.BaseFragment;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.event.TeacherInfoChangeEvent;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import greenDAO.bean.Course;
import greenDAO.bean.StudyWeek;
import greenDAO.dao.DaoSession;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/5 0005.
 */
public class PersonFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.teacher_image)
    CircleImageView teacherImage;
    @Bind(R.id.teacher_nickname)
    TextView teacherNickname;
    @Bind(R.id.teacher_class)
    TextView teacherClass;
    @Bind(R.id.teacher_message)
    LinearLayout teacherMessage;
    @Bind(R.id.teacher_evaluate)
    TextView teacherEvaluate;
    @Bind(R.id.teacher_read)
    TextView teacherRead;
    @Bind(R.id.teacher_opition)
    LinearLayout teacherOpinition;
    @Bind(R.id.teacher_change_psw)
    LinearLayout teacherChangePsw;
    @Bind(R.id.teacher_out)
    LinearLayout teacherOut;
    @Bind(R.id.teacher_about)
    LinearLayout teacherAbout;

    private TeacherMessage model = new TeacherMessage();
    private PopupWindow popupWindow;

    @OnClick(R.id.teacher_about)
    void onAboutClick(){
        startActivity(AboutActivity.class);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.tab_fragment_person;
    }

    public static PersonFragment newInstance() {
        return new PersonFragment();
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        getData();

        teacherMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (model.getData() != null) {
                    Intent intent = new Intent(getActivity(), TeacherChangeActivity.class);
                    intent.putExtra("teacherMessage", model);
                    mActivity.startActivity(intent);
                }

            }
        });

        teacherChangePsw.setOnClickListener(this);
        teacherOpinition.setOnClickListener(this);
        teacherOut.setOnClickListener(this);


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    /**
     * 显示退出popupWindow
     */
    private void showPopupWindow() {
        if (popupWindow == null) {
            TextView drawerLayoutPopupWindowSureTV;
            TextView drawerLayoutPopupWindowCanCelTV;
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.mine_logout_popupwindow, null);
            drawerLayoutPopupWindowSureTV = (TextView) view.findViewById(R.id.drawerLayoutPopupWindowSureTV);
            drawerLayoutPopupWindowCanCelTV = (TextView) view.findViewById(R.id.drawerLayoutPopupWindowCanCelTV);
            drawerLayoutPopupWindowCanCelTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            drawerLayoutPopupWindowSureTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GetUserInfo.loginOut(mActivity);
                    startActivity(LoginActivity.class);
                    DaoSession daoSession = ((MyApplication) getActivity().getApplication()).getDaoSession();
                    daoSession.deleteAll(Course.class);
                    daoSession.deleteAll(StudyWeek.class);
                    mActivity.finish();
                }
            });
            popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        }
        popupWindow.showAtLocation(teacherOut, Gravity.CENTER, 0, 0);

    }

    /**
     * 接收event 刷新界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(TeacherInfoChangeEvent event) {
        if (event.isChanged()) {
            getData();
        }
    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.teacher_change_psw:
                startActivity(TeacherSetPasswordActivity.class);
                break;
            case R.id.teacher_opition:
                startActivity(PersonOptionActivity.class);
                break;
            case R.id.teacher_out:
                showPopupWindow();
                break;
        }
    }

    /**
     * 得到教师个人信息数据
     */
    public void getData() {
        String loginUrl = Constant.URL_TEACHER + "teacher/selectMydata";

        Map<String, String> map = new HashMap<>();
        map.put("teacherId", GetUserInfo.getTeacherId(mActivity));
        map.put("token", GetUserInfo.getToken(mActivity));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast(mActivity.getApplication(), "获取个人信息失败！");
            }

            @Override
            public void onResponse(String response, int id) {

                Log.e("E", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(mActivity.getApplication(), "获取个人信息失败！");
                        return;
                    }

                } catch (JSONException e) {

                }
                Gson gson = new Gson();
                model = gson.fromJson(response, TeacherMessage.class);
                if (model.isSuccess()) {
                    if (model != null) {
                        if (teacherNickname == null) {
                            return;
                        }
                        if (model.getData().getTeachername() == null) {
                            teacherNickname.setText(getResources().getString(R.string.study_nick_name));
                            teacherNickname.setTextColor(getResources().getColor(R.color.hint));
                        } else {
                            teacherNickname.setText(model.getData().getMynickname());
                        }
                        if (model.getData().getPersonalizedsignature() == null) {
                            teacherClass.setText(getResources().getString(R.string.study_personalized_signature));
                            teacherClass.setTextColor(getResources().getColor(R.color.hint));
                        } else {
                            teacherClass.setText(model.getData().getPersonalizedsignature());
                        }
                        teacherEvaluate.setText(model.getData().getBecomments() + "");
                        teacherRead.setText(model.getData().getBeviewed() + "");
                        Glide.with(mActivity)
                                .load(model.getData().getTeacherheadportrait())
                                .placeholder(R.drawable.teacher)
                                .centerCrop()
                                .into(teacherImage);
                    }
                }
            }
        });
    }

}
